
//获取服务器数据
function renderCategory() {
  $.ajax({
    url: '/my/category/list',
    success: function (res) {
     
      if (res.status === 0) {
        let str = ''
        res.data.forEach(item => {
          str += `
          <tr>
               <td>${item.name}</td>
               <td>${item.alias}</td>
               <td>
                   <button type="button" data-id=${item.id} class="bj layui-btn layui-btn-xs">编辑</button>
                   <button type="button" data-id=${item.id} class="sc layui-btn layui-btn-xs layui-btn-danger">删除</button>
               </td>
           </tr>
          `
        });
        $('tbody').html(str)
      }
    }
    
  })
}
renderCategory()
//添加数据
let addIndex;
$('button:contains("添加类别")').on('click', function () {
  addIndex = layer.open({
    type: 1,
    title: '类别添加',
    content: $('.tc').html(),
    area: ['500px', '250px'],
  });   
})
//确定提交到服务器
$('body').on('submit', '#add-form', function (e) {
  e.preventDefault()
  let data = $(this).serialize()
  $.ajax({
    type:'POST',
    url: '/my/category/add',
    data: data,
    success: function (res) {
      if (res.status === 0) {
        layer.msg(res.message)
        renderCategory()
        layer.close(addIndex);
      }
    }
  })
})
//删除功能
$('body').on('click', '.sc', function () {
  let id = $(this).data('id')
  $.ajax({
    type:'GET',
    url: `/my/category/delete?id=${id}`,
    success: function (res) {
      if (res.status === 0) {
        layer.msg(res.message)
        renderCategory()
      }
    }  
  })
})
//编辑功能
let id,bianji;
$('body').on('click', '.bj', function () {
   id = $(this).data('id')
   bianji= layer.open({
    type: 1,
    title: '类别修改',
    content: $('.bianji').html(),
    area: ['500px', '250px'],
  });
  //数据回填
  $.ajax({
    url: '/my/category/list',
    success: function (res) {
      let form = layui.form
      res.data.forEach(function (item) {
        if (item.id === id) {
          form.val('bcd', item)
        }
      })   
    }
  })
})
//编辑提交
$('body').on('submit', '#xg-form', function (e) {
  e.preventDefault()
  let data = $(this).serialize()+'&id='+id
  console.log(data);
  $.ajax({
    type:'POST',
    url: '/my/category/update',
    data: data,
    success: function (res) {
      if (res.status === 0) {
        layer.msg(res.message)
        layer.close(bianji)
        renderCategory()
      }
    }  
  })  
})
